<template>
  <article class="page page-rtsp-player">
    <h4 class="text-center">RTSP播放器</h4>
    <div class="page-body row">
      <div class="col-4">
        <fieldset>
          <legend>参数配置</legend>
          <div class="fieldset-content">
						<div class="alert alert-info">
							本工具基于ffmpeg，需要先行安装ffmpeg，并加入到环境变量。
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">RTSP地址</div>
							<div class="row-flex-main"><input class="form-control" type="text" v-model.trim="videoUrl"
									placeholder="请输入播放地址" /></div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">RTMP端口</div>
							<div class="row-flex-main"><input class="form-control" type="number" v-model.trim="rtmpPort"
									placeholder="RTMP服务端口" /></div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">HTTP端口</div>
							<div class="row-flex-main"><input class="form-control" type="number" v-model.trim="httpPort"
									placeholder="HTTP服务端口" /></div>
						</div>
						<div class="form-group row-flex" align="center">
							<div class="row-flex-prefix">FFmpeg</div>
							<div class="row-flex-main">
								<input class="form-control form-control-sm" type="text" v-model="ffmpegPath" placeholder="ffmpeg路径" readonly />
							</div>
							<div class="row-flex-suffix"><x-button size="small" @click="setPath">选择...</x-button></div>
						</div>
						<div class="form-group form-group-main">
							<textarea class="form-control" v-model="message" placeholder="输出信息" readonly ></textarea>
						</div>
            <div class="form-group">
              <x-button type="primary" block @click="clickHandler">{{ loadingCount > 0 ? '停 止' : '播 放'}}</x-button>
            </div>
          </div>
        </fieldset>
      </div>
      <div class="col-8">
        <fieldset>
          <legend>播放区域</legend>
          <div class="fieldset-content">
            <video :id="id" controls="controls"></video>
          </div>
        </fieldset>
      </div>
    </div>
  </article>
</template>

<script>
const {remote} = global.require('electron')
const {dialog} = remote
const selfWindow= remote.getCurrentWindow()
const {exec} = global.require('child_process')
let flvjs = global.flvjs || null
let treekill = global.treekill || null

export default {
  name: 'rtsp-player',
  data() {
    return {
			id: 'player_' + `${Math.random()}`.substring(2),
			nodeMediaServer: null,
			commandHandle: null,
			flvPlayer: null,
      videoUrl: '',
      rtmpPort: 1987,
      httpPort: 1990,
      message: '',
      ffmpegPath: 'ffmpeg',
      loadingCount: 0
    }
  },
  methods: {
    // 设置ffmpeg文件路径
    setPath () {
      let filePaths = dialog.showOpenDialogSync(selfWindow, {
        title: '选择文件',
        buttonLabel:'确定',
        defaultPath: this.$sharedObject('desktopPath'),
        properties: ['openFile']
      })
      if (filePaths instanceof Array && filePaths.length > 0) {
        this.ffmpegPath = filePaths[0]
      }
    },
    // 点击按钮
    clickHandler() {
      if (this.loadingCount > 0) {
        this.playStop()
      } else {
        this.playStart()
      }
    },
    // 开始
    playStart() {
      if (!this.videoUrl) { return this.$toast('请输入视频地址') }
			if (!flvjs) return
			this.loadingCount = 1
			this.message = ''
			this.message += '启动rtmp和http服务\n'
			this.$sharedObject('nodeMediaServer').start()
			this.nodeMediaServer = this.$sharedObject('nodeMediaServer').getServer()
			this.message += '使用ffmpeg推流\n'
			let command = `chcp 65001 & ${this.ffmpegPath || 'ffmpeg.exe'} -re -i ${this.videoUrl} -c copy -f flv rtmp://localhost:${this.rtmpPort}/live/${this.id}`
			this.commandHandle = exec(command, (error, stdout, stderr) => {
				console.log('commandHandle:', error, stdout, stderr)
				if (error) {
					this.message += `${stderr}\n`
				} else {
					console.log('command:', stdout)
				}
			})
			this.flvPlayerStart()
			// this.commandHandle = spawn(this.ffmpegPath || 'ffmpeg.exe', [
			// 	`-re`, `-i`, `${this.videoUrl}`, `-c`, `copy`, `-f`, `flv`, `rtmp://localhost/live/${this.id}`
			// ])
			// this.commandHandle.stderr.on('data', (err) => {
			// 	this.message += `${err}\n`
			// })
			// this.flvPlayerStart()
    },
    // 结束
    playStop() {
			this.loadingCount = 0
			this.message += '停止rtmp和http服务\n'
			this.$sharedObject('nodeMediaServer').stop()
			this.message += '销毁播放器\n'
			this.flvPlayer && this.flvPlayer.destroy()
			this.message += '终止ffmpeg推流\n'
			treekill && this.commandHandle && treekill(this.commandHandle.pid)
    },
		flvPlayerStart () {
			if (flvjs.isSupported()) {
				let videoElement = document.querySelector(`#${this.id}`)
				this.message += '初始化播放器\n'
				this.flvPlayer = flvjs.createPlayer({
					type: 'flv',
					url: `http://localhost:${this.httpPort}/live/${this.id}.flv`
				})
				this.flvPlayer.attachMediaElement(videoElement)
				this.flvPlayer.load()
				this.flvPlayer.play()
				console.log('flvPlayer:', this.flvPlayer)
			}
		}
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";

.page-rtsp-player {
  display: flex;
  flex-direction: column;

  .row-flex {
    &+.row-flex {
      margin-top: 1em;
    }

    .row-flex-prefix {
      min-width: 5em;
      text-align: right;
    }

    .row-flex-main {
      text-align: left;
    }
  }

  .page-body {
    height: 0;
    flex-grow: 1;
    overflow: hidden;
    position: relative;

    fieldset {
      height: 100%;
    }

    .fieldset-content {
      height: calc(100% - 2em);
      display: flex;
      flex-direction: column;
			position: relative;
			.form-group-main {
				flex-grow: 1;
				textarea {
					display: block;
					width: 100%;
					height: 100%;
					resize: none;
				}
			}
      video {
				.absolute-fullscreen;
				width: 100%;
				height: 100%;
				object-fit: contain;
        background-color: #333;
      }
    }
  }
}
</style>
